package common

import (
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/micro-gfyx-api/http_server/controller"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/errcode"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/dto/common/openapi_dto"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/repository/common"
	utils2 "git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/utils"
	basePb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
	commonService "git.mycaigou.com/gfyx/micro-gfyx-api/service/common"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
	"github.com/goccy/go-json"
	"net/http"
)

type OpenApiController struct {
	controller.BaseController
	createTenantService commonService.CreateTenantServiceIface
}

// NewOpenApiController 开放接口
func NewOpenApiController(
	createTenantService commonService.CreateTenantServiceIface,
) *OpenApiController {
	return &OpenApiController{
		createTenantService: createTenantService,
	}
}

func (c *OpenApiController) RegisterRouter(g *gin.RouterGroup) {
	// 省市雷达商机类型筛选项接口
	g.GET("check-radar-profit", c.checkRadarProfit)

	//开库流程，对接天际运营平台
	g.POST("create-tenant", c.createTenant)
	//销户，对接天际运营平台
	g.POST("remove-tenant", c.removeTenant)
	//获取任务状态，对接天际运营平台
	g.GET("get-task-status", c.getTaskStatus)

	//手动操作，开库销户结果回调天际运营平台
	g.GET("hand-create-tenant-callback", c.createTenantCallback)
	//手动操作，开库
	g.POST("hand-create-tenant", c.createTenant)
}

type checkRadarProfitRequest struct {
	CompanyName string `form:"company_name" binding:"required"`
}

func (c *OpenApiController) checkRadarProfit(ctx *gin.Context) {
	var request checkRadarProfitRequest
	if err := ctx.ShouldBind(&request); err != nil {
		stark.Logger.Errorf(ctx, "http checkRadarProfit 参数错误：%s", err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "公司名称不能为空")
		return
	}

	// 手动写入租户code
	// 给平台用户使用的，固定传租户 code 才能调用通
	ctx.Set(authorize.TENANT_CODE_KEY, "ycg")
	repo := common.NewOptionRepository()
	resp, err := repo.GetTenantProfitByName(ctx, &basePb.GetTenantProfitByNameRequest{CompanyName: request.CompanyName})
	if err != nil {
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	if resp != nil {
		for _, profit := range resp.Profits {
			if profit.ProductCode == "ClueRadarNationwide" || profit.ProductCode == "ClueRadarProvince" {
				c.Success(ctx, map[string]bool{"has_clue_radar_profit": true})
				return
			}
		}
	}

	c.Success(ctx, map[string]bool{"has_clue_radar_profit": false})
}

func (c *OpenApiController) createTenant(ctx *gin.Context) {
	req := &openapi_dto.CreateTenantRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils2.GetValidateErr(req, err))
		return
	}
	reqJson, err := json.Marshal(req)
	stark.Logger.Infof(ctx, "create-tenant-request:%s", string(reqJson))

	res, err := c.createTenantService.CreateTenant(ctx, req)
	if err != nil {
		stark.Logger.Errorf(ctx, "create-tenant err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "接口返回异常")
		return
	}
	ctx.JSON(http.StatusOK, res)
}

func (c *OpenApiController) removeTenant(ctx *gin.Context) {
	req := &openapi_dto.RemoveTenantRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils2.GetValidateErr(req, err))
		return
	}

	res, err := c.createTenantService.RemoveTenant(ctx, req)
	if err != nil {
		stark.Logger.Errorf(ctx, "remove-tenant err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "接口返回异常")
		return
	}
	ctx.JSON(http.StatusOK, res)
}

func (c *OpenApiController) getTaskStatus(ctx *gin.Context) {
	req := &openapi_dto.GetTaskStatusRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils2.GetValidateErr(req, err))
		return
	}

	res, err := c.createTenantService.GetTaskStatus(ctx, req)
	if err != nil {
		stark.Logger.Errorf(ctx, "get-task-status err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "接口返回异常")
		return
	}
	ctx.JSON(http.StatusOK, res)
}

func (c *OpenApiController) createTenantCallback(ctx *gin.Context) {
	req := &openapi_dto.CreateTenantCallbackRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, utils2.GetValidateErr(req, err))
		return
	}

	res, err := c.createTenantService.CreateTenantCallback(ctx, req)
	if err != nil {
		stark.Logger.Errorf(ctx, "get-task-status err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, "接口返回异常")
		return
	}
	ctx.JSON(http.StatusOK, res)
}
